package com.mrlong.mlcamerac;

import android.Manifest;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.net.TrafficStats;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.mrlong.mlcamerac.push.Encoder;
import com.mrlong.mlcamerac.push.PushConnectListenr;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.text.DecimalFormat;
import java.util.List;

import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private final static String TAG = "MainActivity==>";
    private SurfaceView surfaceView;
    private Button btnStart;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    int framerate = 15;
    public static int biterate = 50 * 1000;
    private SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera.setPreviewDisplay(holder);
                camera.startPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            //activity 进入后台的时候 要销毁
            //releaseCamera();
        }
    };
    private Encoder encoder;
    private EditText pushUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.INTERNET,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initView();
                            initSurfaceView();
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    while (true) {
                                        try {
                                            Thread.sleep(2 * 1000);
                                            updateViewData(MainActivity.this);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }.start();
                        }
                    }
                });
    }

    private long rxtxTotal = 0;
    private DecimalFormat showFloatFormat = new DecimalFormat("0.00");

    public void updateViewData(Context context) {
        long tempSum = TrafficStats.getTotalRxBytes()
                + TrafficStats.getTotalTxBytes();
        long rxtxLast = tempSum - rxtxTotal;
        double totalSpeed = rxtxLast * 1000 / 2000d;
        rxtxTotal = tempSum;
        //ttvspeed.setText(showSpeed(totalSpeed));
        Log.e("===>", showSpeed(totalSpeed));
    }

    private String showSpeed(double speed) {
        String speedString;
        if (speed >= 1048576d) {
            speedString = showFloatFormat.format(speed / 1048576d) + "MB/s";
        } else {
            speedString = showFloatFormat.format(speed / 1024d) + "KB/s";
        }
        return speedString;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initCamera();
    }

    private void releaseCamera() {
        if (null != camera) {
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
            camera = null;
            System.gc();
        }
    }

    private void initSurfaceView() {
        surfaceHolder = surfaceView.getHolder();// 不能直接操作SurfaceView，需要通过SurfaceView拿到SurfaceHolder
        surfaceHolder.setKeepScreenOn(true);//使用SurfaceHolder设置屏幕高亮，注意：所有的View都可以设置 设置屏幕高亮
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// 使用SurfaceHolder设置把画面或缓存 直接显示出来
        surfaceHolder.addCallback(callback);
    }

    private void initView() {
        surfaceView = findViewById(R.id.surfaceView);
        btnStart = findViewById(R.id.btnStart);
        btnStart.setOnClickListener(this);
        pushUrl = findViewById(R.id.pushUrl);
    }

    private Camera.Size previewSize;

    private void initCamera() {
        // 打开摄像头并将展示方向旋转90度
        camera = Camera.open(1);
        //camera.setDisplayOrientation(90);
        //设置相机回调数据格式
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPictureFormat(ImageFormat.NV21);
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        boolean flag = false;
        for (Camera.Size size : supportedPreviewSizes) {
            if (size.width == 640 && size.height == 480) {
                previewSize = size;
                flag = true;
                break;
            }
        }
        if (!flag) {
            for (Camera.Size size : supportedPreviewSizes) {
                if (size.width >= 640) {
                    previewSize = size;
                    break;
                }
            }
        }
        parameters.setPreviewSize(previewSize.width, previewSize.height);
        parameters.setPictureSize(previewSize.width, previewSize.height);
        camera.setParameters(parameters);
        //设置数据回调监听器
        camera.setPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                //Log.e(TAG, "数据长度 = " + data.length);
                try {
                    Encoder.getInstance().putYUVData(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private boolean isStart = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStart:
                if (!isStart) {
                    if (null == pushUrl || null == pushUrl.getText() || pushUrl.getText().toString().length() == 0) {
                        Toast.makeText(MainActivity.this, "推流地址不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    encoder = Encoder.getInstance();
                    encoder.init(this,
                            pushUrl.getText().toString().trim(),
                            previewSize.width,
                            previewSize.height,
                            framerate,
                            biterate,
                            new PushConnectListenr() {
                                @Override
                                public void onConnecting() {
                                    Log.e(TAG, "连接中...");
                                }

                                @Override
                                public void onConnectSuccess() {
                                    Log.e(TAG, "成功...");
                                }

                                @Override
                                public void onConnectFail(String msg) {
                                    Log.e(TAG, "失败...");
                                }
                            });
                    encoder.start();
                    isStart = true;
                    btnStart.setText("停止");
                } else {
                    encoder.stop();
                    isStart = false;
                    btnStart.setText("开始");
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        encoder.stop();
        releaseCamera();
    }

}
